package src.dp.easy;

public class no509 {  //斐波那契数

    public int fib(int n) {
        if (n == 0 || n == 1) return n;
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }

    public int fib2(int n) {
        if (n == 0 || n == 1) return n;
        return fib2(n - 1) + fib2(n - 2);
    }

    //压缩状态：由于 fib(n) 只依赖于前两个值，因此可以只用两个变量保存，用不着一整个数组
    public int fib3(int n) {
        if (n <= 1) return n;
        int a = 0, b = 1, res = 0;
        for (int i = 2; i <= n; i++) {
            res = a + b;
            a = b;
            b = res;
        }
        return res;
    }

}
